#!/usr/bin/perl -w
# configure_ejabberd.pm
# Copyright (C) 2006  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information: http://carrierclass.net/
#
use strict; use warnings;

package CCNCore::Provision::Application::jabber_client;
use base qw(CCNCore::Provision::Base);

use CCN::Text;
use CCNCore::Scripting;
use CCNCore::Home;

sub run()
{
    my $self = shift;
    return if $self->p->force_manager;

    # Client side
    # Every machine is a client.
    # Jabber id: s<pk>

    $self->PACKAGE ('libnet-jabber-perl');

    COMMIT_MODULE(ref($self));
}

sub commit()
{
    my $self = shift;
    my $c = shift;
    
    my $SALT = $self->system_salt;

    my $server_pk =
        $self->sql_get(q(SELECT MIN(cdn_downstream_server) FROM server WHERE the_system = ?),
            $self->p->system_pk);
    my $server_name = $self$self->p->make_server_name($server_pk);

    my $env = {
        'USERNAME'      => 's'.$self->p->server_pk,
        'MYHOSTNAME'    => $self->p->server_name,
        'SERVER'        => $server_name,
        'DOMAIN'        => $self$self->p->system_name,
        'PORT'          => 5222,
        'PASSWORD'      => $self->make_password($self->p->server_pk,$SALT,'spool'),
    };

    for my $f (CCNCore::Home::config.'/local/bin/jabber_config.pm')
    {
        template 
                    CCNCore::Home::manager.'/lib/templates/jabber_config.pm',
                    $c->root().$f,
                    $env ;
        $c->commit_file($f);
    }

    # Restart unspool. This is one way to do it.
    my $ps1 = content_of(CCNCore::Home::config.'/local/spool/.SpoolRemote.running');
    if(defined $ps1)
    {
        $self->log("Restarting Unspool (PID=$ps1)\n");
        $ps1 = int($ps1);
        kill 'HUP', $ps1 if $ps1;
    }
    my $ps2 = content_of(CCNCore::Home::config.'/local/spool/.UnspoolRemote.running');
    if(defined $ps2)
    {
        $self->log("Restarting Unspool (PID=$ps2)\n");
        $ps2 = int($ps2);
        kill 'HUP', $ps2 if $ps2;
    }

    # Respawn a new unspool if the current one died
    use CCNCore::Scripting;
    use CCNCore::IPC::SpoolRemote;
    CCNCore::Scripting::CRONTAB q(*/4 * * * * nice -n 1 ).CCNCore::IPC::SpoolRemote::cmd;
    use CCNCore::IPC::UnspoolRemote;
    CCNCore::Scripting::CRONTAB q(*/4 * * * * nice -n 1 ).CCNCore::IPC::UnspoolRemote::cmd;
}

1;
